import { Controller, Get, Post, Body, Param, HttpException, HttpStatus, UseGuards } from '@nestjs/common'
import { MetadataService } from '../services/metadata.service'
import { ModelSchema } from '../entities/model-schema.entity'
import { ApiTags, ApiOperation, ApiBody, ApiResponse, ApiParam } from '@nestjs/swagger'
import { Permissions } from 'src/common/decorators/permissions.decorator'

/**
 * 元数据控制器
 * 提供模型注册、模型列表、模型详情等接口
 * 所有接口均集成权限守卫
 */
@ApiTags('元数据')
@Controller('metadata')
export class MetadataController {
  constructor(private readonly metadataService: MetadataService) {}

  /**
   * 注册新模型
   * @param dto 模型数据 { name, label, fields }
   */
  @Post('models')
  @ApiOperation({ summary: '注册新模型' })
  @ApiBody({
    schema: {
      example: {
        name: 'article',
        label: '文章',
        fields: [
          { name: 'title', type: 'string', label: '标题', required: true },
          { name: 'content', type: 'string', label: '内容' },
          { name: 'published', type: 'boolean', label: '已发布' },
        ],
      },
    },
  })
  @ApiResponse({ status: 201, description: '模型注册成功', type: ModelSchema })
  @Permissions('metadata:model:register')
  async registerModel(@Body() dto: any): Promise<ModelSchema> {
    try {
      return await this.metadataService.registerModel(dto)
    } catch (e) {
      throw new HttpException(e.message, HttpStatus.BAD_REQUEST)
    }
  }

  /**
   * 获取所有模型列表
   */
  @Get('models')
  @ApiOperation({ summary: '获取所有模型列表' })
  @ApiResponse({ status: 200, description: '模型列表', type: [ModelSchema] })
  @Permissions('metadata:model:list')
  async getAllModels(): Promise<ModelSchema[]> {
    return this.metadataService.getAllModels()
  }

  /**
   * 获取指定模型详情
   * @param name 模型名
   */
  @Get('models/:name')
  @ApiOperation({ summary: '获取指定模型详情' })
  @ApiParam({ name: 'name', description: '模型英文名' })
  @ApiResponse({ status: 200, description: '模型详情', type: ModelSchema })
  @Permissions('metadata:model:read')
  async getModel(@Param('name') name: string): Promise<ModelSchema | undefined> {
    return this.metadataService.getModel(name)
  }
}
